use "../2_Data/temp/data_selected_region.dta", clear


local trends trend_prov1 trend_prov3 trend_prov5 trend_prov8 trend_prov10 trend_prov11 trend_prov12 trend_prov14 trend_prov16 trend_prov18 trend_prov19


foreach var of varlist daily_increase tamponi_day ratio2 totale_osp terapia deceduti_day {

use "../2_Data/temp/data_selected_region.dta", clear


levelsof codice_regione, local(prov)

foreach province in `prov' {
    
	gen trend_prov`province'= (codice_regione==`province')*trend*(post==0)
}



reg2hdfe `var' post_election, id1(region_code) id2(time_fe_region)

predict uhat, res

moransi uhat, lat(x_region) lon(y_region) dunit(km) swm(binary) dist(1300) approx // need to account for spatial correlation

reg2hdfespatial `var' post_election `trends', lat(x_region) lon(y_region) timevar(time_fe_region) panelvar(region_code) distcutoff(1300) lagcutoff(110) // maximum feasible values


		matrix P = [.]
		matrix LAT = [.]
		matrix TIME = [.]
		

forvalues lat = 1(25)1300 { // source: https://www.chimica-online.it/come-quando-perche/quanto-e-lunga-l-italia.htm#:~:text=L'Italia%20ha%20uno%20sviluppo,Spada%20nell'isola%20di%20Lampedusa%2C
forvalues time = 0(3)108 { // we have 107 days in the sample

qui { // run it quietly to save time
eststo clear

eststo: reg2hdfespatial `var' post_election `trends', lat(x_region) lon(y_region) timevar(time_fe_region) panelvar(region_code) distcutoff(`lat') lagcutoff(`time')  // needs tmpdir reg2hdfe from SSC to run

estout est1, cells(p)

matrix p1 = r(coefs)
			
			matrix P = [P, p1[1,1]]
			matrix LAT = [LAT, `lat']
			matrix TIME = [TIME, `time']
	
}
di "Distcutoff = `lat'; Lagcutoff = `time'"
}
}

matrix M = [P \ LAT \ TIME]'


clear
		svmat M
		replace M1 = . if M2 == 0 & M3 == 0
		replace M2 = . if M1 == .
		replace M3 = . if M1 == .
		
		
save "../2_Data/temp/heatmap_data.dta", replace


use "../2_Data/temp/heatmap_data.dta", clear
		
local figure _`var'_results_hac_se
		
		heatplot M1 M3 M2,  levels(10) fast colors(cranberry gold, ipolate()) xtitle("Distance cutoff (Km.)", size(large)) ytitle("Lag cutoff (Days)", size(large)) ///
graphregion(fcolor(white) color(white)) scheme(s1mono) legend(subtitle("") size(*1.6) cols(1) region(lcolor(white))) /// 
xlabel(0(100)1300, labsize() angle(30)) ylabel(0(10)110, angle(0) labsize())   // needs palettes from SSC to run "ssc install palette, replace"; also needs colrspace, gtools

}
